package cn.wzg.datastorage;

import static java.net.HttpURLConnection.HTTP_OK;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Objects;

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {
    private BookHelper helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        helper=new BookHelper(this);
    }

    //------------内部存储读写------------------------------------------------
    public void write1(View view) {
        try {
            FileOutputStream fos = openFileOutput("aaa.txt", MODE_PRIVATE);
            fos.write("hello android!".getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void read1(View view) {
        try {
            FileInputStream fis = openFileInput("aaa.txt");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) > 0)
                baos.write(bytes, 0, len);
            String str = baos.toString();
            Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
            fis.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //------------内置外部存储，App私有部分读写------------------------------------
    public void write2(View view) {
        try {
            File filesDir = getExternalFilesDir("");
            assert filesDir != null;
            System.out.println(filesDir.getAbsolutePath());
            File file = new File(filesDir, "bbb.txt");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write("内置的外部存储空间，App私有部分".getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void read2(View view) {
        try {
            File filesDir = getExternalFilesDir("");
            assert filesDir != null;
            System.out.println(filesDir.getAbsolutePath());
            //雷电模拟器：/storage/emulated/0/Android/data/cn.wzg.datastorage/files

            File file = new File(filesDir, "bbb.txt");
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) > 0)
                baos.write(bytes, 0, len);
            String str = baos.toString();
            Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
            fis.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void spSave(View view) {
        SharedPreferences sp = getSharedPreferences("aaa", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("name", "Lisi");
        edit.putInt("age", 20);
        //edit.commit();//官方建议使用apply
        edit.apply();
    }

    public void spRead(View view) {
        SharedPreferences sp = getSharedPreferences("aaa", MODE_PRIVATE);
        String name = sp.getString("name", "");
        int age = sp.getInt("age", 0);
        Toast.makeText(this, name + "," + age, Toast.LENGTH_SHORT).show();
    }

    public void toLogin(View view) {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    public void add(View view) {
        SQLiteDatabase db = helper.getWritableDatabase();
        //方法1
        db.execSQL("insert into book(name,author,price) values('Java基础','zhao',50);");
        //方法2
        ContentValues values=new ContentValues();
        values.put("name","Android开发");
        values.put("author","qian");
        values.put("price",60);
        db.insert("book",null,values);
    }

    public void del(View view) {
        SQLiteDatabase db = helper.getWritableDatabase();
        //方法1
        db.execSQL("delete from book where id=1;");
        //方法2
        db.delete("book","id=2",null);
        //db.delete("book","id=?",new String[]{"2"});
    }

    public void mod(View view) {
        SQLiteDatabase db = helper.getWritableDatabase();
        //方法1
        db.execSQL("update book set name='Java从入门到精通' where id=1;");
        //方法2
        ContentValues values=new ContentValues();
        values.put("name","Android从入门到精通");
        db.update("book",values,"id=?",new String[]{"2"});
    }

    public void query(View view) {
        SQLiteDatabase db = helper.getReadableDatabase();
        //方法1
        Cursor cursor = db.rawQuery("select * from book", null);
        //方法2
        //Cursor cursor = db.query("book", null, null, null, null, null, null);
        while (cursor.moveToNext()){
            String name = cursor.getString(1);
            String author = cursor.getString(2);
            int price=cursor.getInt(3);
            System.out.println(name+","+author+","+price);
        }
        cursor.close();
    }

    //以下内容，学习完内容提供者后讲
    //------------公共空间，使用SAF读写------------------------------------------
    public void createFileSaf(View view) {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // 文件类型
        intent.setType("text/plain");
        // 文件名称
        intent.putExtra(Intent.EXTRA_TITLE, System.currentTimeMillis() + ".txt");
        startActivityForResult(intent, 100);
    }

    public void selectFileSaf(View view) {
        //通过系统的文件浏览器选择一个文件
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        //筛选，只显示可以“打开”的结果，如文件(而不是联系人或时区列表)
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        //过滤只显示图像类型文件
        intent.setType("text/plain");
        startActivityForResult(intent, 200);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri uri = null;
        if (data != null) {
            uri = data.getData();
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                //新创建的文件是空文件，调用修改文件函数往文件写入内容
                alterDocument(uri);
            } else if (requestCode == 200) {
                try {
                    String s = readTextFromUri(uri);
                    Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
                    //同理，拿到uri后，也可以进行文件的删除，修改等操作
                    //deleteFile(uri);
                    //Bitmap bitmap=getBitmapFromUri(uri);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    //修改文件
    private void alterDocument(Uri uri) {
        try {
            ParcelFileDescriptor pfd = getContentResolver().
                    openFileDescriptor(uri, "w");
            FileOutputStream fileOutputStream =
                    new FileOutputStream(pfd.getFileDescriptor());
            fileOutputStream.write(("Storage Access Framework Example").getBytes());
            fileOutputStream.close();
            pfd.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //删除文件
    public void deleteFile(Uri uri) {
        if (uri != null) {
            try {
                DocumentsContract.deleteDocument(getContentResolver(), uri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private String readTextFromUri(Uri uri) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = getContentResolver().openInputStream(uri);
             BufferedReader reader = new BufferedReader(
                     new InputStreamReader(Objects.requireNonNull(inputStream)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }

    private Bitmap getBitmapFromUri(Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }

    //------------公共空间，使用MediaStore读写------------------------------------------
    private void saveBitmap(Bitmap bitmap) {
        if (bitmap == null) return;
        // 获取保存文件的 Uri
        ContentResolver contentResolver = getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
        // 指定保存的文件名，如果不设置，则系统会取当前的时间戳作为文件名
        values.put(MediaStore.Images.Media.DISPLAY_NAME, "test.png");
        Uri insertUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        // 保存图片到 Pictures 目录下
        if (insertUri != null) {
            OutputStream os = null;
            try {
                os = contentResolver.openOutputStream(insertUri);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void downSavePic(View view) {
        String link = "https://www.zzuli.edu.cn/_upload/article/images/38/c3/f9e6289641278d8013330985b20c/40035c74-7257-4c8e-89c6-bf9d431c63fd.jpg";
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(link);//创建URL对象
                    //获取HttpsURLConnection对象
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);//设置超时时间（毫秒）
                    //判断网络访问是否成功
                    if (conn.getResponseCode() == HTTP_OK) {
                        //获取输入流
                        InputStream stream = conn.getInputStream();
                        //从流中获取图片
                        Bitmap bitmap = BitmapFactory.decodeStream(stream);
                        saveBitmap(bitmap);
                    }
                    conn.disconnect();//关闭连接
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
    }

    public void downSaveFile(View view) {
        String link = "https://www.wanandroid.com/article/list/0/json";
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(link);//创建URL对象
                    //获取HttpsURLConnection对象
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);//设置超时时间（毫秒）
                    //判断网络访问是否成功
                    if (conn.getResponseCode() == HTTP_OK) {
                        //获取输入流
                        InputStream stream = conn.getInputStream();
                        ContentValues values = new ContentValues();
                        values.put(MediaStore.MediaColumns.DISPLAY_NAME, "wanandroid.txt");
                        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
                        ContentResolver contentResolver = getContentResolver();
                        Uri uri = contentResolver.insert(MediaStore.Files.getContentUri("external"), values);
                        OutputStream os = contentResolver.openOutputStream(uri);
                        byte[] buffer = new byte[1024];
                        int bytes = stream.read(buffer);
                        while (bytes >= 0) {
                            os.write(buffer, 0, bytes);
                            os.flush();
                            bytes = stream.read(buffer);
                        }
                        os.close();
                        conn.disconnect();
                    }
                    conn.disconnect();//关闭连接
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
    }
}